package com.szh.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author: SongZiHao
 * @date: 2023/1/15
 */
@Controller
public class LoginController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @ResponseBody
    @GetMapping("/getUserInfo")
    public String getUserInfo(@RequestParam("token") String token) {
        String value = redisTemplate.opsForValue().get(token);
        return value;
    }

    @GetMapping(value = "/login.html")
    public String loginPage(@RequestParam("redirect_url") String redirectUrl, Model model,
                            @CookieValue(value = "sso_token", required = false) String ssoToken) {
        if (!StringUtils.isEmpty(ssoToken)) { //ssoToken不为空，说明之前有人登录过，浏览器留下了痕迹
            return "redirect:" + redirectUrl + "?token=" + ssoToken;
        }
        model.addAttribute("redirect_url", redirectUrl);
        return "login";
    }

    @PostMapping(value = "/doLogin")
    public String doLogin(@RequestParam("username") String username,
                          @RequestParam("password") String password,
                          @RequestParam("redirect_url") String redirectUrl,
                          HttpServletResponse response) {
        //登录成功跳转到之前的页面
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            //把登录成功的用户存到Redis中
            String uuid = UUID.randomUUID().toString().replace("-", "");
            redisTemplate.opsForValue().set(uuid, username);
            Cookie cookie = new Cookie("sso_token", uuid);
            response.addCookie(cookie);
            return "redirect:" + redirectUrl + "?token=" + uuid;
        }
        //登录失败，继续展示登录页
        return "login";
    }
}
